#!/usr/bin/env python3

'''
Author       : bopo
Date         : 2020-12-08 10:17:37
LastEditors  : bopo
LastEditTime : 2020-12-08 18:19:19
FilePath     : /stealer/stealer/adapter/douyin.py
Description  :
'''
import logging
import re
from urllib import parse

import requests

from stealer import config
from stealer.logger import log
from . import BaseAdapter

headers = {
    "user-agent": config.USER_AGENT
}

download_headers = {
    "accept": "*/*",
    "accept-language": "zh-CN,zh;q=0.9,ja;q=0.8,en;q=0.7,zh-TW;q=0.6,de;q=0.5,fr;q=0.4,ca;q=0.3,ga;q=0.2",
    "accept-encoding": "identity;q=1, *;q=0",
    "sec-fetch-site": "cross-sit",
    "sec-fetch-mode": "no-cors",
    "sec-fetch-dest": "video",
    "range": "bytes=0-",
    "user-agent": config.USER_AGENT
}


class DouYinAdapter(BaseAdapter):

    def __init__(self, *args, **kwargs):
        self.options = kwargs

    @classmethod
    def get_prefix_pattern(cls) -> str:
        return 'douyin\.com\/'

    @classmethod
    def make_url(cls, index) -> str:
        return f'https://v.douyin.com/{index}'

    def parse(self, url=None, header: bool = True):
        url = url if url else self.link
        log.info(f'url=>{url}')
        res = requests.get(url, headers=headers)

        try:
            iid = re.findall(r"(?<=video/)\d+", res.url)[0]
            log.info(f'iid=>{iid}')
        except ValueError:
            return res.reason

        url = f"https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/"
        res = requests.get(url, params={'item_ids': iid, 'dytk': ''}, headers=headers)

        try:
            vid = res.json()['item_list'][0]['video']['play_addr'].get('uri')
            log.info(f'vid=>{vid}')
        except ValueError:
            return res.reason

        request_params = {
            'video_id': vid,
            'line': 0,
            'ratio': 540,
            'media_type': 4,
            'vr_type': 0,
            'improve_bitrate': 0,
            'is_play_url': 1,
            'is_support_h265': 0,
            'source': 'PackSourceEnum_PUBLISH',
        }

        link = f"https://aweme.snssdk.com/aweme/v1/play/"
        link = "{}?{}".format(link, parse.urlencode(request_params))
        data = {
            'link': link,
            'name': 'name',
            'meta': {
                'headers': download_headers
            }}
        return data
        # return base64.b64encode(json.dumps(data).encode())

    # def fetch(self, output: str = None, stream: bool = True):
    #     return super(DouYinAdapter, self).fetch(output=output, stream=True)

    # def download(self, url=None, filename=None):
    #     return super(DouYinAdapter, self).download(url=url, filename=filename)


if __name__ == '__main__':
    DouYinAdapter().fetch('https://v.douyin.com/J4jS8MN/')
